﻿using Microsoft.AspNetCore.Connections;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuanYijia.Application.ProductionManagement
{
    public class RabbitMQHelper
    {
        //ConnectionFactor  连接工厂对象
        private static ConnectionFactory factory;
        private static object obj = new object();

        //连接rabbitmq 
        //只需要连接一次
        //单例设计模式
        public static IConnection GetConnection()
        {
            // A  B
            if (factory == null)
            {
                // A B
                //锁
                //防止并发
                lock (obj)
                {
                    //A  B
                    if (factory == null)
                    {
                        factory = new ConnectionFactory
                        {
                            
                         

                            HostName = "47.94.104.5",  //连rabbitmq 地址
                            Port = 5672,  //默认端口
                            UserName = "admin",
                            Password = "admin",
                            VirtualHost = "/"
                        };
                    }
                }
            }
            return (IConnection)factory.CreateConnectionAsync();
        }
        //private static readonly Lazy<ConnectionFactory> lazyFactory = new Lazy<ConnectionFactory>(() => new ConnectionFactory
        //{
        //    HostName = "47.94.104.5",  // RabbitMQ 地址
        //    Port = 5672,  // 默认端口
        //    UserName = "admin",
        //    Password = "admin"

        //});

        // 连接RabbitMQ，单例设计模式
        //public static async Task<IConnection> GetConnection()
        //{
        //    var factory = lazyFactory.Value;
        //    return await factory.CreateConnectionAsync();  // 创建连接（同步方法）
        //}
    }
}
